package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */

@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    public static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    //作为redis判断的兜底，基本不会生效

    private void handlerVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();

        RLock simpleRedisLock = redissonClient.getLock("order:" + userId);
        if(! simpleRedisLock.tryLock()){
            log.error("不许重复下单");
        }
        try {
            synchronized (userId.toString().intern()){
            //获取代理对象
            //    IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();  //在子线程，不能去线程拿到代理对象
                proxy.createVoucherOrder(voucherOrder);
            }
        }finally {
            simpleRedisLock.unlock();
        }
    }

    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";

        @Override
        public void run() {
            while (true) {
                try {
                    //获取消息队列中的消息信息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed()));

                    //判断是否拿到消息
                    if (list == null || list.isEmpty()) {
                        //没拿到继续下一没有次循环
                        continue;
                    }
                    //拿到了解析信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    createVoucherOrder(voucherOrder);

                    //ack 确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常：", e);
                    handlerPendingList();
                }
            }
        }

        private void handlerPendingList() {
            String queueName = "stream.orders";
            while (true) {
                try {
                    //获取消息队列中的消息信息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0")));

                    //判断是否拿到消息
                    // 没有异场消息，pend list 的结束循环
                    if (list == null || list.isEmpty()) {
                        break;
                    }
                    //拿到了解析信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    createVoucherOrder(voucherOrder);

                    //ack 确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理pending list异常：", e);
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException ex) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }


    private IVoucherOrderService proxy;

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        //用lua写redis做判断
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.EMPTY_LIST,
                voucherId.toString(),userId.toString(),String.valueOf(orderId));
        int r = result.intValue();
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足":"不能重复下单略略");
        }

        proxy = (IVoucherOrderService) AopContext.currentProxy();  //在子线程，不能去线程拿到代理对象

        return Result.ok(orderId);
    }




    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //一人一单判断
        Long userId = voucherOrder.getUserId();
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder).count();

        if (count > 0) {
            log.error("一人限购一单哦");
            return;
        }

        boolean flag = seckillVoucherService.update()
                .setSql("stock = stock -1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock",0) //乐观锁cas法解决超卖
                .update();

        if (!flag) {
            log.error("抢购失败");
            return;
        }
        save(voucherOrder);
    }
}


//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
//    private class VoucherOrderHandler implements Runnable{
//
//        @Override
//        public void run() {
//            try {
//                VoucherOrder voucherOrder = orderTasks.take();
//                handlerVoucherOrder(voucherOrder);
//            } catch (Exception e) {
//                log.error("处理订单异常：",e);
//            }
//        }
//    }



//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        Long userId = UserHolder.getUser().getId();
//        //用lua写redis做判断
//        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.EMPTY_LIST,
//                voucherId.toString(),userId.toString());
//        int r = result.intValue();
//        if (r != 0) {
//            return Result.fail(r == 1 ? "库存不足":"不能重复下单略略");
//        }
//        long orderId = redisIdWorker.nextId("order");
//
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setVoucherId(voucherId);
//        voucherOrder.setUserId(userId);
//
//        // 保存阻塞队列
//        orderTasks.add(voucherOrder);
//        proxy = (IVoucherOrderService) AopContext.currentProxy();  //在子线程，不能去线程拿到代理对象
//
//        return Result.ok(orderId);
//    }


//    public Result seckillVoucher(Long voucherId) {
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//
//        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
//            return Result.fail("秒杀还没开始");
//        }
//        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀已经结束");
//        }
//
//        if(voucher.getStock() < 1){
//            return Result.fail("秒杀卷库存不足");
//        }
//
//
//        Long userId = UserHolder.getUser().getId();
//        //拿锁
//        // SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId,stringRedisTemplate);
//        RLock simpleRedisLock = redissonClient.getLock("order:" + userId);
//        if(! simpleRedisLock.tryLock()){
//            return Result.fail("不许重复下单略略");
//        }
//        try {
//            synchronized (userId.toString().intern()) {
//                //获取代理对象
//                IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//                return proxy.createVoucherOrder(voucherId);
//            }
//        }finally {
//            simpleRedisLock.unlock();
//        }
//    }